﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using Wuqi.Webdiyer;
using System.Text;

namespace ZWZ.Web.WebAdmin.UCtrs
{
    public partial class CtrList : System.Web.UI.UserControl
    {
        protected int IndexColumnWidth = 25;
        protected int OperateColumnWidth
        {
            get { if (ViewState["OperateColumnWidth"] != null) { return Convert.ToInt32(ViewState["OperateColumnWidth"]); } else { return 80; } }
            set { ViewState["OperateColumnWidth"] = value; }
        }
        protected int RowHeight = 25;
        /// <summary>
        /// 当数据高度大于设置高度时显示高度，否则不显示高度，高度由数据高度加空白高度决定
        /// </summary>
        protected bool ShowHeight
        {
            get { if (ViewState["ShowHeight"] != null) { return Convert.ToBoolean(ViewState["ShowHeight"]); } else { return true; } }
            set { ViewState["ShowHeight"] = value; }
        }
        [Browsable(true)]
        [Category("行为")]
        public bool ShowEditButton
        {
            get { if (ViewState["ShowEditButton"] != null) { return Convert.ToBoolean(ViewState["ShowEditButton"]); } else { return false; } }
            set { ViewState["ShowEditButton"] = value; }
        }
        [Category("行为")]
        [Browsable(true)]
        public bool ShowDeleteButton
        {
            get { if (ViewState["ShowDeleteButton"] != null) { return Convert.ToBoolean(ViewState["ShowDeleteButton"]); } else { return false; } }
            set { ViewState["ShowDeleteButton"] = value; }
        }
        [Category("行为")]
        [Browsable(true)]
        public bool ShowCustomButton
        {
            get { if (ViewState["ShowCustomButton"] != null) { return Convert.ToBoolean(ViewState["ShowCustomButton"]); } else { return false; } }
            set { ViewState["ShowCustomButton"] = value; }
        }
        [Category("行为")]
        [Browsable(true)]
        public bool ShowPagerAlways
        {
            get { return MPager.AlwaysShow; }
            set { MPager.AlwaysShow = value; }
        }
        [Category("行为")]
        [Browsable(true)]
        public bool ShowEmptyRows
        {
            get { return ViewState["ShowEmptyRows"] == null ? true : Convert.ToBoolean(ViewState["ShowEmptyRows"]); }
            set { ViewState["ShowEmptyRows"] = value; }
        }
        [Category("行为")]
        [Browsable(true)]
        public bool ShowIndexColumn
        {
            get { return ViewState["ShowIndexColumn"] == null ? true : Convert.ToBoolean(ViewState["ShowIndexColumn"]); }
            set { ViewState["ShowIndexColumn"] = value; }
        }
        [Browsable(true)]
        [Category("行为")]
        public string ClientScript_DeleteMethord
        {
            get { return ViewState["ClientScript_DeleteMethord"] == null ? null : ViewState["ClientScript_DeleteMethord"].ToString(); }
            set { ViewState["ClientScript_DeleteMethord"] = value; }
        }
        [Browsable(true)]
        [Category("行为")]
        public string ClientScript_EditMenthord
        {
            get { return ViewState["ClientScript_EditMenthord"] == null ? null : ViewState["ClientScript_EditMenthord"].ToString(); }
            set { ViewState["ClientScript_EditMenthord"] = value; }
        }
        [Browsable(true)]
        [Category("数据")]
        public string ColumnKeyFieldName
        {
            get { return ViewState["ColumnKeyFieldName"] == null ? null : ViewState["ColumnKeyFieldName"].ToString(); }
            set { ViewState["ColumnKeyFieldName"] = value; }
        }
        [Browsable(true)]
        public int Height { get; set; }
        [Browsable(true)]
        [Category("行为")]
        public int PageSize
        {
            get { return MPager.PageSize; }
            set { MPager.PageSize = value; }
        }
        [Browsable(true)]
        [Category("行为")]
        public int CurrentPageIndex
        {
            get { return MPager.CurrentPageIndex; }
            set { MPager.CurrentPageIndex = value; }
        }
        [Browsable(false)]
        public int RecordCount
        {
            get { return MPager.RecordCount; }
            set { MPager.RecordCount = value; }
        }
        public int EmptyRowMaxCount { get; set; }
        [Category("数据")]
        [Browsable(true)]
        public object DataSource
        {
            get { return RptListData.DataSource; }
            set { RptListData.DataSource = value; }
        }
        [Browsable(false)]
        public List<ListColumn> Columns
        {
            get
            {
                if (ViewState["Columns"] == null)
                {
                    ViewState["Columns"] = new List<ListColumn>();
                }
                return ViewState["Columns"] as List<ListColumn>;
            }
            set
            {
                ViewState["Columns"] = value;
            }
        }
        public List<SummaryColumn> SummaryColumns
        {
            get
            {
                if (ViewState["SummaryColumns"] == null)
                {
                    ViewState["SummaryColumns"] = new List<SummaryColumn>();
                }
                return ViewState["SummaryColumns"] as List<SummaryColumn>;
            }
            set
            {
                ViewState["SummaryColumns"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //绑定事件
            MPager.PageChanging += PageChanging;
            RptListData.ItemCommand += ItemCommand;
        }
        protected void RptListData_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                //取得控件
                Literal LtrListData = e.Item.FindControl("LtrListData") as Literal;
                ImageButton BtnUpdate = e.Item.FindControl("BtnUpdate") as ImageButton;
                ImageButton BtnDelete = e.Item.FindControl("BtnDelete") as ImageButton;
                LinkButton BtnCustom = e.Item.FindControl("BtnCustom") as LinkButton;

                //绑定行数据
                StringBuilder DataHtml = new StringBuilder();
                Type DataType = e.Item.DataItem.GetType();
                foreach (var column in Columns)
                {
                    var value = GetItemValue(e.Item, column.FieldName);
                    var kvalue = string.Empty;
                    if (!string.IsNullOrEmpty(ColumnKeyFieldName))
                    {
                        kvalue = GetItemValue(e.Item, ColumnKeyFieldName).ToString();
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(column.OnClientClick)) { throw new Exception("ColumnKeyFieldName为空！"); }
                    }
                    value = (value == null ?
                            string.Empty :
                            string.IsNullOrEmpty(column.DataFormat) ?
                                value.ToString() :
                                string.Format(column.DataFormat, value));
                    DataHtml.AppendLine(string.Format("<td title='{0}' style='width:{1};{2};' {4} >{3}</td>",
                        column.ShowToolTip ? value : string.Empty,
                        column.Width,
                        (string.IsNullOrEmpty(column.OnClientClick) ? string.Empty : "cursor:pointer;") + column.Style,
                        value,
                        string.IsNullOrEmpty(column.OnClientClick)
                        ? string.Empty
                        : "onclick=\"" + string.Format(column.OnClientClick, kvalue) + "\" "));
                }
                LtrListData.Text = DataHtml.ToString();

                //绑定操作按钮
                if (!ShowDeleteButton) { BtnDelete.Visible = false; }
                if (!ShowEditButton) { BtnUpdate.Visible = false; }
                if (!ShowCustomButton) { BtnCustom.Visible = false; }

                //绑定主键
                if (!string.IsNullOrEmpty(ColumnKeyFieldName))
                {
                    //绑定CommandArgument
                    string KeyFileValue = DataType.GetProperty(ColumnKeyFieldName).GetValue(e.Item.DataItem, null).ToString();
                    BtnDelete.CommandArgument = KeyFileValue;
                    BtnUpdate.CommandArgument = KeyFileValue;

                    //绑定ClientScript
                    if (!string.IsNullOrEmpty(ClientScript_EditMenthord))
                    {
                        BtnUpdate.OnClientClick = string.Format("{0}('{1}');return false;", ClientScript_EditMenthord, KeyFileValue);
                    }
                    if (!string.IsNullOrEmpty(ClientScript_DeleteMethord))
                    {
                        BtnDelete.OnClientClick = string.Format("if(confirm('确认要删除吗？')){{0}('{1}');}else{ return false;}", ClientScript_EditMenthord, KeyFileValue);
                    }
                    else
                    {
                        BtnDelete.OnClientClick = string.Format("return confirm('确认要删除吗？');");
                    }
                }
            }
            if (ItemDataBond != null) { ItemDataBond(sender, e); }
        }
        protected void ShowEmptyRow()
        {
            StringBuilder EmptyRow = new StringBuilder();
            ///如果不显示高度就要显示空白行，高度有数据和空白行决定
            if (!ShowHeight)
            {
                int TotalRowHeight = RowHeight * RptListData.Items.Count;
                int emptyrows = Convert.ToInt32((Height - TotalRowHeight + 10) / RowHeight);
                for (int emptyrowindex = RptListData.Items.Count + 1; emptyrowindex <= RptListData.Items.Count + emptyrows; emptyrowindex++)
                {
                    EmptyRow.Append(string.Format("<tr {0}>",
                        emptyrowindex % 2 == 0 ? "class='ood'" : ""));
                    if (ShowIndexColumn) {
                        EmptyRow.Append(string.Format("<td style='width: {1}px;'>{0}</td>",
                        emptyrowindex, IndexColumnWidth));
                    }
                    for (int emptycolunmindex = 0; emptycolunmindex < Columns.Count; emptycolunmindex++)
                    {
                        EmptyRow.Append(string.Format("<td width='{0}'>&nbsp;</td>", Columns[emptycolunmindex].Width == null ? "auto" : Columns[emptycolunmindex].Width));
                    }
                    EmptyRow.Append("<td style='width: " + OperateColumnWidth + "px;'>&nbsp;</td></tr>");
                }
            }
            LtrEmptyRow.Text = EmptyRow.ToString();
        }
        protected void ShowSummaryRow()
        {
            if (SummaryColumns.Count > 0)
            {
                StringBuilder summayrow = new StringBuilder();
                summayrow.Append("<table class='list' width='100%'><tr><td  class='list-sum list-sum-index' style='width:" + IndexColumnWidth + "px;'>&nbsp;</td>");
                for (int colindex = 0; colindex < Columns.Count; colindex++)
                {
                    var sumcol = SummaryColumns.Where(i => i.tdIndex == colindex).FirstOrDefault();
                    var column = Columns[colindex];
                    if (sumcol != null)
                    {
                        summayrow.AppendLine(string.Format("<td title='{0}' class='list-sum' style='width:{1};{2}'>{3}</td>", sumcol.Tootip, column.Width, sumcol.Style, sumcol.Text));
                    }
                    else
                    {
                        summayrow.AppendLine(string.Format("<td class='list-sum' style='width:{0};'>&nbsp;</td>", column.Width));
                    }
                }
                summayrow.Append("<td class='list-sum list-sum-operate' style='width:" + (ShowHeight ? (OperateColumnWidth + 17) : OperateColumnWidth) + "px;'>&nbsp;</td></tr></table>");
                LtrSummaryRow.Text = summayrow.ToString();
            }
        }
        protected void ShowHeaderRow()
        {
            StringBuilder HeaderHtml = new StringBuilder();
            HeaderHtml.AppendLine("<table class='list' width='100%'><tr>");
            if (ShowIndexColumn)
            {
                HeaderHtml.AppendLine("<td class='list-header' style='width:" + IndexColumnWidth + "px;'>#</td>");
            }
            foreach (var column in Columns)
            {
                HeaderHtml.AppendLine(string.Format("<td class='list-header' style='width:{0};'>{1}</td>", column.Width, column.Caption));
            }
            HeaderHtml.AppendLine("<td class='list-header' style='width: " + (ShowHeight ? (OperateColumnWidth + 17) : OperateColumnWidth) + "px;'>操作</td></tr></table>");
            LtrListHeader.Text = HeaderHtml.ToString();
        }
        protected void CheckScrollBar()
        {
            if (ShowHeight)
            {
                List_DataContainer.Style.Add(HtmlTextWriterStyle.OverflowY, "scroll");
                List_DataContainer.Style.Add(HtmlTextWriterStyle.Height, Height + "px");
            }
            else
            {
                List_DataContainer.Style.Add(HtmlTextWriterStyle.OverflowY, "auto");
                List_DataContainer.Style.Add(HtmlTextWriterStyle.Height, "auto");
            }
        }
        public override void DataBind()
        {
            RptListData.DataBind();
            if (RecordCount == 0) { RecordCount = RptListData.Items.Count; }
            ///判断是否显示滚动条和高度
            ///当设置了高度，并且高度比所有数据高度要大时不显示高度
            ///否则显示高度和滚动条
            ShowHeight = true;
            if (Height > 0)
            {
                int TotalRowHeight = RowHeight * RptListData.Items.Count;
                if (TotalRowHeight < Height)
                {
                    ShowHeight = false;
                }
            }
            ///如果设置了显示空白行，就显示
            if (ShowEmptyRows) { ShowEmptyRow(); }
            ShowHeaderRow();
            ShowSummaryRow();
            CheckScrollBar();
            if (ShowPagerAlways) { LabSum.Text = string.Format("第{0}页（共{1}页，{2}条数据）&nbsp;&nbsp;", CurrentPageIndex, RecordCount / PageSize + 1, RecordCount); }
            else { LabSum.Text = string.Format("共{0}条数据&nbsp;&nbsp;", RecordCount); }
            base.DataBind();
        }
        [Browsable(true)]
        public event PageChangingEventHandler PageChanging;
        [Browsable(true)]
        public event RepeaterCommandEventHandler ItemCommand;
        [Browsable(true)]
        public event RepeaterItemEventHandler ItemDataBond;
        public object GetItemValue(RepeaterItem item, string FieldName)
        {
            Type DataType = item.DataItem.GetType();
            var proterty = DataType.GetProperty(FieldName);
            if (proterty == null) throw new Exception("未找到属性：" + FieldName);
            return proterty.GetValue(item.DataItem, null);
        }
    }

    [Serializable]
    public class ListColumn
    {
        private bool _ShowToolTip = true;
        public string Caption { get; set; }
        public string Width { get; set; }
        public string FieldName { get; set; }
        public string DataFormat { get; set; }
        public string Style { get; set; }
        public bool ShowToolTip { get { return _ShowToolTip; } set { _ShowToolTip = value; } }
        public string OnClientClick { get; set; }
    }

    [Serializable]
    public class SummaryColumn
    {
        public int tdIndex { get; set; }
        public string Text { get; set; }
        public string Tootip { get; set; }
        public string Style { get; set; }
    }
}